var DBFactory = require('../conn/DBFactory');
var flashSaleDao = module.exports;
var request = require('request');

flashSaleDao.spiderDDQ = function(data, cb) {
    if(!data) cb(new Error(500));
    var arr = [];
    for(var k in data.ddq) {
        arr.push(k);
    }
    arr.sort();
    formatData(arr, data.ddq, 0);
    cb(null, '开始爬取ddq数据！');
}

function formatData(arr, ddq, i) {
    var result = ddq[arr[i]];
    var goodsList = [];
    result.forEach(function (g) {
        var good = [];
        good.push(g.pic);
        good.push(g.title);
        good.push(g.d_title);
        good.push(g.id);
        good.push(g.yuanjia);
        good.push(g.jiage);
        good.push(g.miaoshu);
        good.push(g.paiqi);
        if(g.quan_id.length == 0 ) {
            good.push(g.jihua_link);
        } else {
            good.push(g.quan_id);
        }
        good.push(g.quan_jine);
        good.push(g.quan_num);
        good.push(g.quan_time);
        good.push(g.xiaoliang);
        good.push((parseFloat(g.jiage) * parseFloat(g.yongjin) / 100).toFixed(2));
        good.push(g.yongjin);
        goodsList.push(good);
    });

    if(goodsList.length > 0 ) {
        checkGoodsList(arr, ddq, i, goodsList);
    } else {
        if(i < arr.length-1) {
            ++i;
            formatData(arr, ddq, i);
        } else {
            return;
        }
    }
}

function checkGoodsList(arr, ddq, i, goodsList) {//这里goodsList一定有
    var dtkIds = [];
    var start_time = goodsList[0][7];
    goodsList.forEach(function (goodInfo) {
        dtkIds.push(goodInfo[3]);
    });
    console.log('执行');
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            console.log("insertFlashSale err:" + error);
        } else {
            var sql = 'select dtkId from flash_sale where start_time = ? and dtkId IN ? ';
            connection.query(sql, [start_time,[dtkIds]],
                function(err, result){
                    if(err) {
                        console.log('第：'+ i + '  err: ' + err);
                        connection.release();
                    } else {//找到的都是已经存在的
                        connection.release();

                        if (!result || result.length <= 0) {//如果都不存在，则可以去全加入
                            insertFlashSale(arr, ddq, i, goodsList);
                            return;
                        }

                        if (result && result.length >= goodsList.length) {//如果都存在，进行下次循环
                            setTimeout(function(){
                                if(i < arr.length-1) {
                                    ++i;
                                    formatData(arr, ddq, i);
                                } else {
                                    return;
                                }
                            }, 1500);
                            return;
                        }

                        var newGoodList = []; //找不存在的去加入
                        goodsList.forEach(function (goodInfo) {
                            for (var i = 0; i < result.length; i++) {
                                var exitGoodInfo = result[i];
                                if (goodInfo[3] == exitGoodInfo.dtkId) break;
                            }
                            if (i == result.length) newGoodList.push(goodInfo) //不存在加入
                        });
                        insertFlashSale(arr, ddq, i, newGoodList);

                    }
                });
        }
    });
}

function insertFlashSale(arr, ddq, i, goodsList) {
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            console.log("insertFlashSale err:" + error);
        } else {
            var sql = 'replace into flash_sale(`pictUrl`,`title`,`goodShortTitle`,`dtkId`,' +
                ' `zkPrice`,`couponAfterpri`,`descr`,`start_time`,`hiddenActivityId`,`hiddenAmount`,' +
                ' `hiddenTotalCount`,`hiddenEndTime`,`biz30day`,`tkCommFee`,`tkRate`) VALUES ? ';
            connection.query(sql, [goodsList],
                function(err, result){
                    if(err) {
                        console.log('第：'+ i + '  err: ' + err);
                        connection.release();
                    } else {
                        console.log('插入了' + result.affectedRows + '条！');
                        connection.release();
                        setTimeout(function(){
                            if(i < arr.length-1) {
                                ++i;
                                formatData(arr, ddq, i);
                            } else {
                                return;
                            }
                        }, 1500);
                    }
                });
        }
    });
}

flashSaleDao.spiderAuctionId = function(cb) {
    getDtkId();
    cb(null, '开始爬取auctionId !');
}

function getDtkId() {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log("getDtkId err:" + error);
        } else {
            var sql = 'select dtkId from flash_sale where NOW() > start_time  and auctionId is null  limit 20';
            connection.query(sql, [],
                function(err, result){
                    if(err) {
                        console.log('获取dtkId失败！ ERR： ' + err);
                        connection.release();
                    } else {
                        if(result.length > 0) {
                            getAuctionId(result, 0);
                        } else {
                            return;
                        }
                        connection.release();
                    }
                });
        }
    });
}

function getAuctionId(result, i) {
    if(result[i] && result[i].dtkId != undefined) {
        var url = 'http://api.dataoke.com/index.php?r=port/index&appkey=169foxqf9m&v=2&id=' + result[i].dtkId;
        request({url: url, method:'GET'}, function(error, response, body){
            if(error && !response && response.statusCode != 200 && !body) {
                console.log('获取商品dtkId:'+ result[i].dtkId + ' err :  ' + error);
                return;
            } else {
                try {
                    var gInfo = JSON.parse(body).result;
                    if(gInfo != null && gInfo.GoodsID) {
                        doUpdateAuctionId(result[i].dtkId, gInfo.GoodsID);
                        setTimeout(function(){
                            ++i;
                            getAuctionId(result, i);
                        }, 1000);
                    } else {
                        delFlashSale(result[i].dtkId);
                        setTimeout(function(){
                            ++i;
                            getAuctionId(result, i);
                        }, 800);
                    }
                } catch(e) {
                    console.log('获取auctionId失败 ' + e);
                }
            }
        });

    } else {
        setTimeout(function(){
            getDtkId();
        }, 800);
    }
}

function doUpdateAuctionId(dtkId, auctionId) {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log("doUpdateAuctionId err:" + error);
        } else {
            var sql ='update flash_sale set auctionId = ? where dtkId = ? ';
            connection.query(sql, [auctionId, dtkId],
                function(err, result){
                    if(err) {
                        console.log('ERR： ' + err);
                        connection.release();
                    } else {
                        console.log('更新auctionId成功！' + result.affectedRows + '条！');
                        connection.release();
                    }
                });
        }
    });
}

function delFlashSale(dtkId) {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log("delFlashSale err:" + error);
        } else {
            var sql ='delete from flash_sale where dtkId = ? ';
            connection.query(sql, [dtkId],
                function(err, result){
                    if(err) {
                        console.log('ERR： ' + err);
                        connection.release();
                    } else {
                        console.log('删除无效商品成功！' + result.affectedRows + '条！');
                        connection.release();
                    }
                });
        }
    });
}

function getDDQTotal(data, cb) {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log("getDDQTotal err:" + error);
        } else {
            var sql ='select count(*) as count from flash_sale where start_time = ? ';
            connection.query(sql, [data.start_time],
                function(err, result){
                    if(err) {
                        console.log('ERR： ' + err);
                        connection.release();
                    } else {
                        var list = {};
                        list.total = result[0].count
                        connection.release();
                        if(parseInt(list.total) > 0) {
                            getDDQGoods(data, list, cb);
                        } else {
                            cb(null, list);
                        }
                    }
                });
        }
    });
}

function getDDQGoods(data, list, cb) {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log("getDDQTotal err:" + error);
        } else {
            var sql ='select *,descr as adTitle from flash_sale where start_time = ? limit ? , ?';
            connection.query(sql, [data.start_time, data.start, data.size],
                function(err, result){
                    if(err) {
                        console.log('ERR： ' + err);
                        connection.release();
                    } else {
                        list.data = result;
                        connection.release();
                        cb(null, list);
                    }
                });
        }
    });
}

flashSaleDao.getDDQGoods = function(data, cb) {
    if(!data) cb(new Error(500));
    getDDQTotal(data, cb);
}

flashSaleDao.canSpider = function(cb) {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log("canSpider err:" + error);
        } else {
            var sql = 'select count(*) as count from flash_sale where NOW() > start_time  and auctionId is null ';
            connection.query(sql, [],
                function(err, result){
                    if(err) {
                        console.log('获取dtkId失败！ ERR： ' + err);
                        connection.release();
                    } else {
                        cb(null, result[0].count);
                        connection.release();
                    }
                });
        }
    });
}